import { useState, useEffect } from 'react';
import { Modal, Transfer, message } from 'antd';
import { get, post } from '../services/api';

function EnrollmentModal({ visible, onClose, classInfo }) {
  const [students, setStudents] = useState([]);
  const [targetKeys, setTargetKeys] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (visible && classInfo) {
      fetchStudentsAndEnrollments();
    }
  }, [visible, classInfo]);

  const fetchStudentsAndEnrollments = async () => {
    setLoading(true);
    try {
      // 获取所有学生
      const allStudents = await get('students');
      
      // 格式化学生数据供Transfer组件使用
      const formattedStudents = allStudents.map(student => ({
        key: student.student_id,
        title: `${student.student_name} (${student.student_id})`,
        description: student.student_name,
      }));
      
      // 获取已选课的学生ID
      const enrolledStudentIds = classInfo.students ? 
        classInfo.students.map(s => s.student_id) : [];
      
      setStudents(formattedStudents);
      setTargetKeys(enrolledStudentIds);
    } catch (error) {
      console.error('获取学生信息失败:', error);
      message.error('获取学生信息失败');
    } finally {
      setLoading(false);
    }
  };

  const handleTransferChange = (newTargetKeys) => {
    setTargetKeys(newTargetKeys);
  };

  const handleOk = async () => {
    setLoading(true);
    try {
      // 这里需要后端提供批量更新选课的接口
      // 暂时用循环调用单个添加接口
      const currentEnrolled = classInfo.students ? 
        classInfo.students.map(s => s.student_id) : [];
      
      // 找出新增的学生
      const toAdd = targetKeys.filter(id => !currentEnrolled.includes(id));
      
      // 添加新学生到班级
      for (const studentId of toAdd) {
        await post(`classes/${classInfo.class_id}/students`, { student_id: studentId });
      }
      
      message.success('选课更新成功');
      onClose(true); // 传入true表示需要刷新数据
    } catch (error) {
      console.error('更新选课失败:', error);
      message.error('更新选课失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      title={`选课管理 - ${classInfo?.class_name}`}
      open={visible}
      onOk={handleOk}
      onCancel={() => onClose(false)}
      width={800}
      confirmLoading={loading}
      okText="确定"
      cancelText="取消"
    >
      <div style={{ marginBottom: 16 }}>
        <p>班级：{classInfo?.class_name}</p>
        <p>学期：{classInfo?.semester}</p>
        <p>教室：{classInfo?.location}</p>
      </div>
      
      <Transfer
        dataSource={students}
        titles={['未选课学生', '已选课学生']}
        targetKeys={targetKeys}
        onChange={handleTransferChange}
        render={item => item.title}
        listStyle={{
          width: 300,
          height: 400,
        }}
        operations={['选课', '退课']}
        showSearch
        locale={{
          itemUnit: '人',
          itemsUnit: '人',
          searchPlaceholder: '搜索学生',
          notFoundContent: '无数据',
        }}
      />
    </Modal>
  );
}

export default EnrollmentModal;